package com.eveinfo.api.transaction;

import java.text.ParseException;
import java.util.LinkedList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.eveinfo.api.AbstractApiHandler;
import com.eveinfo.api.ApiError;

public class WalletTransactionHandler extends AbstractApiHandler<ApiWallet> {

	private LinkedList<String> where = new LinkedList<String>();

	public WalletTransactionHandler() {
		super();
		response = new ApiWallet();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("rowset")) {
			where.addFirst(attributes.getValue("name"));
		}else if (value.equals("row")) {
			if(where.getFirst().equals("transactions")){
				ApiWalletTransaction transaction = new ApiWalletTransaction();
				transaction.setClientID(Long.parseLong(attributes.getValue("clientID")));
				transaction.setClientName(attributes.getValue("clientName"));
				transaction.setPrice(Double.parseDouble(attributes.getValue("price")));
				transaction.setQuantity(Long.parseLong(attributes.getValue("quantity")));
				transaction.setStationID(Long.parseLong(attributes.getValue("stationID")));
				transaction.setStationName(attributes.getValue("stationName"));
				try {
					transaction.setTransactionDateTime(sdf.parse(attributes.getValue("transactionDateTime")));
				} catch (ParseException e) {
					e.printStackTrace();
					error = new ApiError();
					error.setError(e.getMessage());
				}
				transaction.setTransactionID(Long.parseLong(attributes.getValue("transactionID")));
				transaction.setTransactionType(attributes.getValue("transactionType"));
				transaction.setTypeID(Long.parseLong(attributes.getValue("typeID")));
				transaction.setTypeName(attributes.getValue("typeName"));
				response.addWalletTransaction(transaction);
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("rowset")) {
			where.removeFirst();
		}
	}
}
